<template>
  <div class="activity-area">
    <!-- 筛选栏 -->
    <el-card shadow="never" class="filter-card">
      <el-form :model="filters" inline>
        <el-form-item label="分类">
          <el-select v-model="filters.category" placeholder="选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="费用">
          <el-select v-model="filters.is_free" placeholder="费用类型" clearable>
            <el-option label="免费活动" value="true" />
            <el-option label="付费活动" value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="filters.tags"
            multiple
            placeholder="选择标签"
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索活动标题或描述"
            clearable
            style="width: 200px"
            @keyup.enter="searchActivities"
          >
            <template #append>
              <el-button @click="searchActivities">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchActivities">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20">
      <!-- 活动列表 -->
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>学习活动</span>
              <div class="header-actions">
                <el-select v-model="sortBy" @change="fetchActivities" style="width: 120px; margin-right: 12px">
                  <el-option label="最新发布" value="-created_at" />
                  <el-option label="活动时间" value="time" />
                  <el-option label="最热门" value="hot" />
                  <el-option label="参与人数" value="participants" />
                </el-select>
                <el-button type="primary" @click="createActivity">
                  <el-icon><Plus /></el-icon>
                  发起活动
                </el-button>
              </div>
            </div>
          </template>

          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部活动" name="all">
              <div v-loading="loading">
                <el-scrollbar height="600px" v-if="activities.length > 0">
                  <div class="activity-list">
                    <el-card 
                      v-for="activity in activities" 
                      :key="activity.id" 
                      class="activity-item"
                      shadow="hover"
                    >
                      <!-- 活动封面图 -->
                      <div v-if="activity.cover_image" class="activity-cover">
                        <el-image
                          :src="activity.cover_image"
                          fit="cover"
                          style="width: 100%; height: 200px"
                        />
                      </div>

                      <div class="activity-header">
                        <h3>{{ activity.title }}</h3>
                        <div class="activity-actions">
                          <el-tag :type="getStatusType(activity.status)">
                            {{ getStatusLabel(activity.status) }}
                          </el-tag>
                          <el-tag v-if="activity.category" type="info" size="small">
                            {{ getCategoryLabel(activity.category) }}
                          </el-tag>
                        </div>
                      </div>

                      <div class="activity-content">
                        <p>{{ activity.description }}</p>
                        
                        <!-- 活动详细信息 -->
                        <div class="activity-info">
                          <div class="info-item">
                            <el-icon><Calendar /></el-icon>
                            <span>{{ formatDateTime(activity.time) }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ activity.location }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><User /></el-icon>
                            <span>{{ activity.participants_count }}人参与</span>
                            <span v-if="activity.max_participants > 0">
                              / {{ activity.max_participants }}人
                            </span>
                          </div>
                          <div v-if="activity.fee > 0" class="info-item">
                            <el-icon><Money /></el-icon>
                            <span>￥{{ activity.fee }}</span>
                          </div>
                          <div v-else class="info-item">
                            <el-icon><Money /></el-icon>
                            <span class="free-tag">免费</span>
                          </div>
                        </div>

                        <!-- 活动标签 -->
                        <div class="activity-tags" v-if="activity.tags && activity.tags.length > 0">
                          <el-tag 
                            v-for="tag in activity.tags" 
                            :key="tag"
                            size="small"
                            effect="plain"
                          >
                            {{ tag }}
                          </el-tag>
                        </div>
                      </div>

                      <div class="activity-footer">
                        <div class="activity-meta">
                          <div class="creator-info">
                            <el-avatar :size="24" :src="activity.creator_avatar" />
                            <span>{{ activity.creator_name }}</span>
                          </div>
                          <div class="activity-stats">
                            <span>
                              <el-icon><View /></el-icon>
                              {{ activity.view_count }}
                            </span>
                            <span>
                              <el-icon><ChatDotRound /></el-icon>
                              {{ activity.comments_count }}
                            </span>
                            <span>
                              <el-icon><Star /></el-icon>
                              {{ activity.favorites_count }}
                            </span>
                          </div>
                        </div>
                        
                        <div class="activity-buttons">
                          <el-button
                            size="small"
                            :icon="activity.favorited ? 'StarFilled' : 'Star'"
                            :type="activity.favorited ? 'warning' : 'default'"
                            @click="handleFavoriteActivity(activity)"
                          >
                            {{ activity.favorited ? '已收藏' : '收藏' }}
                          </el-button>
                          
                          <el-button 
                            :type="activity.joined ? 'success' : 'primary'"
                            :disabled="activity.is_full && !activity.joined"
                            @click="handleJoinActivity(activity)"
                          >
                            <template v-if="activity.is_full && !activity.joined">
                              已满员
                            </template>
                            <template v-else>
                              {{ activity.joined ? '取消参加' : '立即参加' }}
                            </template>
                          </el-button>
                          
                          <el-button 
                            type="info" 
                            @click="viewActivityDetail(activity.id)"
                          >
                            查看详情
                          </el-button>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </el-scrollbar>
                <el-empty v-else description="暂无活动" />
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="我发起的" name="created">
              <div v-loading="loading">
                <el-scrollbar height="600px" v-if="activities.length > 0">
                  <div class="activity-list">
                    <el-card 
                      v-for="activity in activities" 
                      :key="activity.id" 
                      class="activity-item"
                      shadow="hover"
                    >
                      <!-- 和上面类似的结构，但添加编辑删除按钮 -->
                      <div class="activity-header">
                        <h3>{{ activity.title }}</h3>
                        <div class="activity-actions">
                          <el-button-group>
                            <el-button size="small" @click="editActivity(activity)">
                              <el-icon><Edit /></el-icon>
                              编辑
                            </el-button>
                            <el-button size="small" type="danger" @click="deleteActivity(activity)">
                              <el-icon><Delete /></el-icon>
                              删除
                            </el-button>
                          </el-button-group>
                        </div>
                      </div>
                      
                      <!-- 其他内容与上面相同 -->
                      <div class="activity-content">
                        <p>{{ activity.description }}</p>
                        <div class="activity-info">
                          <div class="info-item">
                            <el-icon><Calendar /></el-icon>
                            <span>{{ formatDateTime(activity.time) }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ activity.location }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><User /></el-icon>
                            <span>{{ activity.participants_count }}人参与</span>
                          </div>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </el-scrollbar>
                <el-empty v-else description="还没有创建过活动" />
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="我参与的" name="joined">
              <div v-loading="loading">
                <el-scrollbar height="600px" v-if="activities.length > 0">
                  <div class="activity-list">
                    <el-card 
                      v-for="activity in activities" 
                      :key="activity.id" 
                      class="activity-item"
                      shadow="hover"
                    >
                      <div class="activity-header">
                        <h3>{{ activity.title }}</h3>
                        <el-tag type="success">已参加</el-tag>
                      </div>
                      <div class="activity-content">
                        <p>{{ activity.description }}</p>
                        <div class="activity-info">
                          <div class="info-item">
                            <el-icon><Calendar /></el-icon>
                            <span>{{ formatDateTime(activity.time) }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ activity.location }}</span>
                          </div>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </el-scrollbar>
                <el-empty v-else description="还没有参加过活动" />
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="我收藏的" name="favorited">
              <div v-loading="loading">
                <el-scrollbar height="600px" v-if="activities.length > 0">
                  <div class="activity-list">
                    <el-card 
                      v-for="activity in activities" 
                      :key="activity.id" 
                      class="activity-item"
                      shadow="hover"
                    >
                      <div class="activity-header">
                        <h3>{{ activity.title }}</h3>
                        <el-tag type="warning">已收藏</el-tag>
                      </div>
                      <div class="activity-content">
                        <p>{{ activity.description }}</p>
                        <div class="activity-info">
                          <div class="info-item">
                            <el-icon><Calendar /></el-icon>
                            <span>{{ formatDateTime(activity.time) }}</span>
                          </div>
                          <div class="info-item">
                            <el-icon><Location /></el-icon>
                            <span>{{ activity.location }}</span>
                          </div>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </el-scrollbar>
                <el-empty v-else description="还没有收藏过活动" />
              </div>
            </el-tab-pane>
          </el-tabs>

          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="total > 0">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息栏 -->
      <el-col :span="8">
        <!-- 活动日历 -->
        <el-card shadow="hover" class="calendar-card">
          <template #header>
            <div class="card-header">
              <span>活动日历</span>
            </div>
          </template>
          <el-calendar v-model="currentDate">
            <template #dateCell="{ data }">
              <div class="calendar-cell">
                <span :class="{ 'current-day': isToday(data.day) }">
                  {{ data.day.split('-').slice(-1)[0] }}
                </span>
                <div class="event-dots">
                  <template v-for="event in getEventsForDate(data.day)" :key="event.id">
                    <el-tooltip :content="event.title" placement="top">
                      <span
                        class="event-dot"
                        :style="{ backgroundColor: event.color }"
                        @click="viewActivityDetail(event.id)"
                      ></span>
                    </el-tooltip>
                  </template>
                </div>
              </div>
            </template>
          </el-calendar>
        </el-card>

        <!-- 热门活动 -->
        <el-card shadow="hover" class="hot-activities">
          <template #header>
            <div class="card-header">
              <span>热门活动</span>
            </div>
          </template>
          <el-scrollbar height="300px">
            <div
              v-for="activity in hotActivities"
              :key="activity.id"
              class="hot-activity-item"
              @click="viewActivityDetail(activity.id)"
            >
              <div class="hot-activity-info">
                <h4>{{ activity.title }}</h4>
                <p>{{ activity.description }}</p>
                <div class="hot-activity-meta">
                  <span>{{ activity.participants_count }}人参与</span>
                  <el-tag size="small" effect="plain">{{ getCategoryLabel(activity.category) }}</el-tag>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>

        <!-- 活动统计 -->
        <el-card shadow="hover" class="stats-card">
          <template #header>
            <div class="card-header">
              <span>我的统计</span>
            </div>
          </template>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-number">{{ userStats.created }}</div>
              <div class="stat-label">创建的活动</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.joined }}</div>
              <div class="stat-label">参与的活动</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userStats.favorited }}</div>
              <div class="stat-label">收藏的活动</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑活动' : '创建新活动'"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="newActivity" 
        label-width="100px"
        :rules="activityRules"
        ref="activityFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="title">
              <el-input v-model="newActivity.title" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动分类" prop="category">
              <el-select v-model="newActivity.category" placeholder="选择分类">
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动描述" prop="description">
          <el-input type="textarea" v-model="newActivity.description" :rows="3" placeholder="请输入活动描述" />
        </el-form-item>

        <el-form-item label="详细内容">
          <el-input type="textarea" v-model="newActivity.content" :rows="5" placeholder="详细介绍活动内容（可选）" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="time">
              <el-date-picker
                v-model="newActivity.time"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="newActivity.end_time"
                type="datetime"
                placeholder="选择结束时间（可选）"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动地点" prop="location">
          <el-input v-model="newActivity.location" placeholder="请输入活动地点" />
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="newActivity.location_detail" placeholder="详细地址（可选）" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大人数">
              <el-input-number 
                v-model="newActivity.max_participants" 
                :min="0" 
                placeholder="0表示不限制"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动费用">
              <el-input-number 
                v-model="newActivity.fee" 
                :min="0" 
                :precision="2"
                placeholder="0表示免费"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系方式">
          <el-input v-model="newActivity.contact_info" placeholder="联系方式（可选）" />
        </el-form-item>

        <el-form-item label="参与要求">
          <el-input type="textarea" v-model="newActivity.requirements" placeholder="参与要求或注意事项（可选）" />
        </el-form-item>

        <el-form-item label="封面图片">
          <el-input v-model="newActivity.cover_image" placeholder="封面图片URL（可选）" />
        </el-form-item>

        <el-form-item label="活动标签">
          <el-select
            v-model="newActivity.tags"
            multiple
            placeholder="选择标签"
            allow-create
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="活动状态">
          <el-radio-group v-model="newActivity.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="published">发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitActivity" :loading="submitting">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 活动详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="活动详情"
      width="70%"
      :close-on-click-modal="false"
    >
      <div v-if="selectedActivity" v-loading="detailLoading">
        <!-- 活动详情内容 -->
        <div class="activity-detail">
          <div v-if="selectedActivity.cover_image" class="detail-cover">
            <el-image
              :src="selectedActivity.cover_image"
              fit="cover"
              style="width: 100%; height: 300px"
            />
          </div>
          
          <div class="detail-header">
            <h2>{{ selectedActivity.title }}</h2>
            <div class="detail-meta">
              <el-tag :type="getStatusType(selectedActivity.status)">
                {{ getStatusLabel(selectedActivity.status) }}
              </el-tag>
              <el-tag type="info">{{ getCategoryLabel(selectedActivity.category) }}</el-tag>
            </div>
          </div>

          <div class="detail-content">
            <p>{{ selectedActivity.description }}</p>
            <div v-if="selectedActivity.content" class="detail-full-content">
              <h4>详细内容</h4>
              <p>{{ selectedActivity.content }}</p>
            </div>
          </div>

          <div class="detail-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="开始时间">
                {{ formatDateTime(selectedActivity.time) }}
              </el-descriptions-item>
              <el-descriptions-item label="结束时间" v-if="selectedActivity.end_time">
                {{ formatDateTime(selectedActivity.end_time) }}
              </el-descriptions-item>
              <el-descriptions-item label="活动地点">
                {{ selectedActivity.location }}
              </el-descriptions-item>
              <el-descriptions-item label="详细地址" v-if="selectedActivity.location_detail">
                {{ selectedActivity.location_detail }}
              </el-descriptions-item>
              <el-descriptions-item label="参与人数">
                {{ selectedActivity.participants_count }}
                <span v-if="selectedActivity.max_participants > 0">
                  / {{ selectedActivity.max_participants }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="活动费用">
                <span v-if="selectedActivity.fee > 0">￥{{ selectedActivity.fee }}</span>
                <span v-else class="free-tag">免费</span>
              </el-descriptions-item>
              <el-descriptions-item label="创建者">
                {{ selectedActivity.creator_name }}
              </el-descriptions-item>
              <el-descriptions-item label="联系方式" v-if="selectedActivity.contact_info">
                {{ selectedActivity.contact_info }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="selectedActivity.requirements" class="detail-requirements">
            <h4>参与要求</h4>
            <p>{{ selectedActivity.requirements }}</p>
          </div>

          <div v-if="selectedActivity.tags && selectedActivity.tags.length > 0" class="detail-tags">
            <h4>活动标签</h4>
            <el-tag 
              v-for="tag in selectedActivity.tags" 
              :key="tag"
              style="margin-right: 8px"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            :type="selectedActivity?.favorited ? 'warning' : 'default'"
            @click="handleFavoriteActivity(selectedActivity)"
          >
            {{ selectedActivity?.favorited ? '取消收藏' : '收藏活动' }}
          </el-button>
          <el-button 
            type="primary"
            :disabled="selectedActivity?.is_full && !selectedActivity?.joined"
            @click="handleJoinActivity(selectedActivity)"
          >
            {{ selectedActivity?.joined ? '取消参加' : '立即参加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { activityApi } from '@/api/activity'

// 基础数据
const activeTab = ref('all')
const currentDate = ref(new Date())
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedActivityId = ref(null)
const selectedActivity = ref(null)
const isEditing = ref(false)
const loading = ref(false)
const detailLoading = ref(false)
const submitting = ref(false)
const sortBy = ref('-created_at')

// 表单引用
const activityFormRef = ref()

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 列表数据
const activities = ref([])
const hotActivities = ref([])

// 筛选条件
const filters = reactive({
  category: '',
  status: '',
  is_free: '',
  tags: [],
  keyword: '',
  location: ''
})

// 用户统计
const userStats = reactive({
  created: 0,
  joined: 0,
  favorited: 0
})

// 新活动表单
const newActivity = ref({
  title: '',
  description: '',
  content: '',
  time: '',
  end_time: '',
  location: '',
  location_detail: '',
  category: '',
  max_participants: 0,
  fee: 0,
  contact_info: '',
  requirements: '',
  cover_image: '',
  tags: [],
  status: 'published'
})

// 表单验证规则
const activityRules = {
  title: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入活动描述', trigger: 'blur' }],
  time: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  category: [{ required: true, message: '请选择活动分类', trigger: 'change' }]
}

// 分类选项
const categories = [
  { label: '运动健身', value: 'sports' },
  { label: '学习交流', value: 'study' },
  { label: '娱乐休闲', value: 'entertainment' },
  { label: '志愿服务', value: 'volunteer' },
  { label: '旅游出行', value: 'travel' },
  { label: '美食聚餐', value: 'food' },
  { label: '艺术文化', value: 'art' },
  { label: '科技数码', value: 'tech' },
  { label: '其他', value: 'other' }
]

// 状态选项
const statusOptions = [
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '进行中', value: 'ongoing' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
]

// 可选标签
const availableTags = [
  '前端', '后端', '算法', '数据库', '人工智能', '技术分享', '项目实战',
  '运动', '健身', '跑步', '瑜伽', '音乐', '电影', '美食', '旅游'
]

// 工具函数
const getCategoryLabel = (value) => {
  const category = categories.find(cat => cat.value === value)
  return category ? category.label : '其他'
}

const getStatusLabel = (value) => {
  const status = statusOptions.find(s => s.value === value)
  return status ? status.label : value
}

const getStatusType = (status) => {
  const typeMap = {
    'draft': 'info',
    'published': 'success',
    'ongoing': 'warning',
    'completed': '',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const isToday = (dateString) => {
  const today = new Date().toISOString().split('T')[0]
  return dateString === today
}

// API 调用函数
const fetchActivities = async () => {
  try {
    loading.value = true
    const params = {
      type: activeTab.value,
      page: currentPage.value,
      page_size: pageSize.value,
      sort: sortBy.value,
      ...filters
    }

    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || (Array.isArray(params[key]) && params[key].length === 0)) {
        delete params[key]
      }
    })

    const response = await activityApi.getActivities(params)
    activities.value = response.data || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

const fetchHotActivities = async () => {
  try {
    const response = await activityApi.getActivities({ 
      sort: 'hot', 
      page_size: 5 
    })
    hotActivities.value = response.data || []
  } catch (error) {
    console.error('获取热门活动失败:', error)
  }
}

const fetchUserStats = async () => {
  try {
    const [created, joined, favorited] = await Promise.all([
      activityApi.getActivities({ type: 'created', page_size: 1 }),
      activityApi.getActivities({ type: 'joined', page_size: 1 }),
      activityApi.getActivities({ type: 'favorited', page_size: 1 })
    ])
    
    userStats.created = created.total || 0
    userStats.joined = joined.total || 0
    userStats.favorited = favorited.total || 0
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 事件处理函数
const searchActivities = () => {
  currentPage.value = 1
  fetchActivities()
}

const resetFilters = () => {
  Object.keys(filters).forEach(key => {
    if (Array.isArray(filters[key])) {
      filters[key] = []
    } else {
      filters[key] = ''
    }
  })
  currentPage.value = 1
  fetchActivities()
}

const createActivity = () => {
  isEditing.value = false
  newActivity.value = {
    title: '',
    description: '',
    content: '',
    time: '',
    end_time: '',
    location: '',
    location_detail: '',
    category: '',
    max_participants: 0,
    fee: 0,
    contact_info: '',
    requirements: '',
    cover_image: '',
    tags: [],
    status: 'published'
  }
  dialogVisible.value = true
}

const editActivity = (activity) => {
  isEditing.value = true
  newActivity.value = { ...activity }
  dialogVisible.value = true
}

const submitActivity = async () => {
  try {
    await activityFormRef.value.validate()
    submitting.value = true
    
    if (isEditing.value) {
      await activityApi.updateActivity(newActivity.value.id, newActivity.value)
      ElMessage.success('更新成功')
    } else {
      await activityApi.createActivity(newActivity.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchActivities()
    fetchHotActivities()
    fetchUserStats()
  } catch (error) {
    if (error.response) {
      console.error('表单验证失败或API错误:', error)
      ElMessage.error(isEditing.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

const deleteActivity = async (activity) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除活动"${activity.title}"吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await activityApi.deleteActivity(activity.id)
    ElMessage.success('删除成功')
    fetchActivities()
    fetchUserStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const viewActivityDetail = async (activityId) => {
  try {
    detailLoading.value = true
    selectedActivityId.value = activityId
    const response = await activityApi.getActivityDetail(activityId)
    selectedActivity.value = response
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  } finally {
    detailLoading.value = false
  }
}

const handleJoinActivity = async (activity) => {
  try {
    const response = await activityApi.toggleJoin(activity.id)
    const action = response.joined ? '参加' : '取消参加'
    
    // 更新活动状态
    activity.joined = response.joined
    activity.participants_count += response.joined ? 1 : -1
    
    // 更新详情对话框中的活动
    if (selectedActivity.value && selectedActivity.value.id === activity.id) {
      selectedActivity.value.joined = response.joined
      selectedActivity.value.participants_count = activity.participants_count
    }
    
    ElMessage.success(`${action}成功`)
    fetchUserStats()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleFavoriteActivity = async (activity) => {
  try {
    const response = await activityApi.toggleFavorite(activity.id)
    const action = response.favorited ? '收藏' : '取消收藏'
    
    // 更新活动状态
    activity.favorited = response.favorited
    activity.favorites_count += response.favorited ? 1 : -1
    
    // 更新详情对话框中的活动
    if (selectedActivity.value && selectedActivity.value.id === activity.id) {
      selectedActivity.value.favorited = response.favorited
      selectedActivity.value.favorites_count = activity.favorites_count
    }
    
    ElMessage.success(`${action}成功`)
    fetchUserStats()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  currentPage.value = 1
  fetchActivities()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchActivities()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchActivities()
}

const getEventsForDate = (date) => {
  return activities.value.filter(activity => {
    const activityDate = new Date(activity.time).toISOString().split('T')[0]
    return activityDate === date
  }).map(activity => ({
    id: activity.id,
    title: activity.title,
    color: activity.joined ? '#67C23A' : activity.favorited ? '#E6A23C' : '#409EFF'
  }))
}

// 监听筛选条件变化
watch(
  () => [filters.category, filters.status, filters.is_free],
  () => {
    currentPage.value = 1
    fetchActivities()
  }
)

// 生命周期钩子
onMounted(() => {
  fetchActivities()
  fetchHotActivities()
  fetchUserStats()
})
</script>

<style scoped>
.activity-area {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-item {
  border: 1px solid var(--el-border-color-lighter);
  transition: all 0.3s;
}

.activity-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.activity-cover {
  margin-bottom: 16px;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.activity-header h3 {
  margin: 0;
  font-size: 18px;
}

.activity-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.activity-content {
  margin-bottom: 16px;
}

.activity-info {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  margin: 12px 0;
  color: var(--el-text-color-secondary);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.free-tag {
  color: var(--el-color-success);
  font-weight: bold;
}

.activity-tags {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  flex-wrap: wrap;
}

.activity-footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.activity-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-stats {
  display: flex;
  gap: 16px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.activity-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.activity-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.calendar-card {
  margin-bottom: 20px;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 4px;
}

.calendar-cell .current-day {
  color: var(--el-color-primary);
  font-weight: bold;
}

.event-dots {
  display: flex;
  gap: 4px;
  justify-content: center;
  margin-top: 4px;
  flex-wrap: wrap;
}

.event-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  cursor: pointer;
  transition: transform 0.2s;
}

.event-dot:hover {
  transform: scale(1.5);
}

.hot-activities {
  margin-bottom: 20px;
}

.hot-activity-item {
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  cursor: pointer;
  transition: background-color 0.2s;
}

.hot-activity-item:hover {
  background-color: var(--el-fill-color-light);
}

.hot-activity-item:last-child {
  border-bottom: none;
}

.hot-activity-info h4 {
  margin: 0 0 8px;
  font-size: 16px;
}

.hot-activity-info p {
  margin: 0 0 8px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-activity-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.stats-card {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.activity-detail {
  padding: 20px 0;
}

.detail-cover {
  margin-bottom: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-header h2 {
  margin: 0 0 12px;
  font-size: 24px;
}

.detail-meta {
  display: flex;
  gap: 8px;
}

.detail-content {
  margin-bottom: 20px;
}

.detail-full-content {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.detail-full-content h4 {
  margin: 0 0 12px;
  color: var(--el-text-color-primary);
}

.detail-info {
  margin-bottom: 20px;
}

.detail-requirements,
.detail-tags {
  margin-bottom: 20px;
}

.detail-requirements h4,
.detail-tags h4 {
  margin: 0 0 12px;
  color: var(--el-text-color-primary);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .activity-info {
    flex-direction: column;
    gap: 8px;
  }
  
  .activity-buttons {
    flex-direction: column;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>